#!/usr/bin/env node

/**
 * Module dependencies.
 */
//在本地的命令行执行 node ./trigger_jenkins.js , 或者把此命令放到package.json的script字段
const {
	Command
} = require('commander');
const program = new Command();
const request = require('request')
const cp = require('child_process');
const util = require('util');
const exec = util.promisify(cp.exec);
let environmental = 'test'
// console.log(program)

program.version('0.0.1')
	.description('这是一个命令行工具')
	.option('-project,--project [name]', 'build you develop project name')
	.option('-token,--apitoken [apitoken]', 'send your api token')
	.option('-author,--author [name]', 'send your author')
	.option('-trigger,--triggerName [name]', 'send your triggerName')
	.option('-branch,--gitBranch [name]', 'send your gitBranch/tags')
	.option('-autotag,--autotag [name]', 'auto creat your tags');

program.on('--help', function() {
	console.log('')
	console.log('Examples:');
	console.log('  $ custom-help --help');
	console.log('  $ custom-help -h');
});

// error on unknown commands
program
	.command('setup [env]')
	.description('run setup commands for all envs')
	.action(async function(env, options) {
		const mode = options.setup_mode || "normal";
		env = env || 'all';
		console.log('setup for %s env(s) with %s mode', env, mode);
		environmental = env;
		//生成tagname       
		try {
			if (program.autotag) {
				const tagName = `d${format_time(new Date().getTime(),'yyyyMMddhhmmss')}`;
				await exec(`git tag -a ${tagName} -m "${tagName}"`)
				await exec(`git push origin --tags`)
				program.gitTagName = `refs/tags/${tagName}`
				console.log('gitTagName--->', program.gitTagName)
			}
			//目前只有测试和开发允许默认构建dev_branch分支
			if (env == 'test' || env == 'dev') {
				autoJenkis()
			}
			//如果是正式环境一定需要配置对应的分支或者tag
			if (env == 'build' && program.gitBranch && program.gitBranch !== 'xx') {
				autoJenkis()
			}
		} catch (error) {
			console.log('error--->', error)
		}
	});

program.parse(process.argv);


function format_time(value, type) {
	if (!value) return null
	let time
	if (value.constructor === Date) {
		time = value
	} else {
		time =
			value.toString().length > 10 ?
			new Date(parseInt(value)) :
			new Date(parseInt(value) * 1000)
	}
	let formatTime = type ? type : 'yyyy-MM-dd hh:mm:ss'
	let date = {
		'M+': time.getMonth() + 1,
		'd+': time.getDate(),
		'h+': time.getHours(),
		'm+': time.getMinutes(),
		's+': time.getSeconds(),
		'q+': Math.floor((time.getMonth() + 3) / 3),
		'S+': time.getMilliseconds()
	}
	if (/(y+)/i.test(formatTime)) {
		formatTime = formatTime.replace(
			RegExp.$1,
			(time.getFullYear() + '').substr(4 - RegExp.$1.length)
		)
	}
	for (let k in date) {
		if (new RegExp('(' + k + ')').test(formatTime)) {
			formatTime = formatTime.replace(
				RegExp.$1,
				RegExp.$1.length == 1 ?
				date[k] :
				('00' + date[k]).substr(('' + date[k]).length)
			)
		}
	}
	return formatTime
}

function autoJenkis() {
	let apiToken = program.token || '115ab8105eb625e8e0523f8ea387924aba' //个人的apitoken , 路径:jenkins界面右上角用户名->设置->添加新Token
	let author = program.author || 'zhangli' //用户名
	let project = program.project || 'vue-webim-test' // 项目名
	let headerStr = `http://${author}:${apiToken}@192.168.197.95:8080/job/${project}/buildWithParameters`
	let triggerName = program.triggerName || 'jenikis@rfchina.com' //jenkins->项目->配置->构建触发器->触发远程构建->填写你的身份验证令牌
	let gitBranch = program.gitBranch || program.gitTagName || '*/dev_branch'
	let url = headerStr + `?token=${triggerName}&GIT_BRANCH=${encodeURI(gitBranch)}` //uploadComponentName为要带过去的参数,可以去掉 
	console.log(url)
	// 触发更新
	request({
		url,
		method: "get",
		json: true,
		headers: {
			"content-type": "application/json"
		}
	}, function(error, response, body) {
		console.log()
		if (error) {
			console.log('触发jenkins编译失败', error)
		} else {
			console.log('触发jenkins编译成功')
		}
	})
}


// autoJenkis()
